/**
 * Created by dy on 2017/5/25.
 */
var WIDTH = document.body.clientWidth;
var HEIGHT = document.body.clientHeight;
var snakes = [];
var snakeLen = 10;
var r = 15;
var fx = getRandom(0,1,'');
window.onload = function () {
    var canvas = $("#canvas").get(0);
    canvas.width = WIDTH;
    canvas.height = HEIGHT;
    var cxt = canvas.getContext('2d');
    initSnake();
    setInterval(function () {
        render(cxt);
        update();
    },50);
};

/*
* 初始化游戏
* */
function render(cxt) {
    cxt.clearRect(0,0,WIDTH,HEIGHT);
    drawBg(cxt);
    drawBgline(cxt);
    renderSnake(cxt);
}
/*
* 生成初始小蛇
* */
function initSnake() {
    var x = getRandom(r*snakeLen,WIDTH-r*snakeLen,0);
    var y = getRandom(r*snakeLen,HEIGHT-r*snakeLen,0);
    for(var i = 0;i<snakeLen;i++){
        if(fx == 1) {
            y += r;
        }else{
            x += r;
        }
        var oneSnake = {
            x:x,
            y:y,
            r:r
        };
        snakes.push(oneSnake);
    }
}
/*
* 渲染小蛇
* */
function renderSnake(cxt) {
    cxt.save();
    for(var i = 0;i<snakes.length;i++) {
        cxt.beginPath();
        cxt.fillStyle = "red";
        cxt.arc(snakes[i].x,snakes[i].y,snakes[i].r,0,2*Math.PI);
        cxt.fill();
    }
    cxt.restore();
}
/*
* 小蛇运动
* */
function update() {
    var x = snakes[0].x;
    var y = snakes[0].y;
    if(fx){
        y += r;
    }else{
        x += r;
    }
    $(document).keyup(function (e) {
       if(e.keyCode == 37){
           x -= r;
       }else if(e.keyCode == 38){
            y -= r;
       }else if(e.keyCode == 39){
           x += r;
       }else if(e.keyCode == 40){
           y += r;
       }
    });
    var one = {
        x:x,
        y:y,
        r:r
    };
    snakes.unshift(one);
    snakes.pop();
}

/*
* 背景绘制
* */
function drawBg(cxt) {
    cxt.save();
    cxt.beginPath();
    cxt.fillStyle = "rgb(237,237,245)";
    cxt.fillRect(0,0,WIDTH,HEIGHT);
    cxt.restore();
}

/*
* 绘制背景棋盘格
* */
function drawBgline(cxt) {
    cxt.save();
    cxt.strokeStyle = "rgb(226,226,234)";
    cxt.lineWidth = 3;
    var len = 50;
    var x = HEIGHT*len/WIDTH;
    for(var i = 0;i<len;i++){
        cxt.beginPath();
        cxt.moveTo(0,HEIGHT/x*(i+1));
        cxt.lineTo(WIDTH,HEIGHT/x*(i+1));
        cxt.stroke();
        cxt.beginPath();
        cxt.moveTo(WIDTH/len*(i+1),0);
        cxt.lineTo(WIDTH/len*(i+1),HEIGHT);
        cxt.stroke();
    }
    cxt.restore();
}